<!-- 组件使用方法见readme -->

<template>
  <div class="body">
    <div class="search">
      <el-button type="primary" @click="toshow" :icon="icon" size="small">筛选</el-button>
      <el-button type="success" icon="el-icon-folder-add" v-if="add" @click="toAdd" size="small">新增</el-button>
    </div>
    <el-form
      v-show="show"
      :model="searchForm"
      ref="searchForm"
      label-width="100px"
      label-position="right"
    >
      <el-form-item
        v-for="(item) in title"
        :key="item.key"
        :label="item.value"
        :placeholder="item.placeholder"
        v-model="searchForm[item['key']]"
        class="search-item"
      >
        <el-input
          v-if="item['type']=='textarea'"
          type="textarea"
          v-model="searchForm[item['key']]"
          :placeholder="item.placeholder"
        ></el-input>
        <el-input
          v-if="item['type']=='text'"
          type="text"
          :maxlength="item.maxlength"
          v-model="searchForm[item['key']]"
          :placeholder="item.placeholder"
          autocomplete="on"
          :show-word-limit="item.showLimit"
          @keyup.enter.native="submitForm('searchForm')"
        ></el-input>
        <div v-if="item['type']=='select'" class="myselect">
          <el-select
            v-model="searchForm[item['key']]"
            :placeholder="item.placeholder"
            :multiple="item.multiple"
            @change="change"
            clearable
            filterable
            @keyup.enter.native="submitForm('searchForm')"
          >
            <el-option
              v-for="selectitem in item.data"
              :key="selectitem.id"
              :label="selectitem.name"
              :value="selectitem.id"
            ></el-option>
          </el-select>
        </div>
        <div v-if="item['type']=='timepicker'">
          <el-date-picker
            v-model="searchForm[item['key']]"
            type="daterange"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="请选择开始日期"
            end-placeholder="请选择结束日期"
          ></el-date-picker>
        </div>
        <div v-if="item['type']=='datatimepicker'">
          <el-date-picker
            v-model="searchForm[item['key']]"
            type="datetimerange"
            value-format="timestamp"
            range-separator="至"
            start-placeholder="请选择开始时间"
            end-placeholder="请选择结束时间"
          ></el-date-picker>
        </div>
      </el-form-item>
      <el-form-item class="search-ope">
        <el-button v-if="needReset" @click="resetForm('searchForm')" size="small" class="reset">重置</el-button>
        <el-button type="primary" icon="el-icon-search" size="small" @click="submitForm('searchForm')">搜索</el-button>
        <el-button v-if="needexport" icon="el-icon-upload2" type="primary"  size="small" @click="toExport">导出</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { objToUrl, getPreSubmitData, urlToObj } from "@/utils";
export default {
  name: "Search",
  props: {
    title: {
      type: Object,
      default: () => { return {} }
    }, // 筛选条件
    searchForm: {
      type: Object,
      default: () => { return {} }
    }, // 筛选字段
    add: {
      type: Boolean,
      default: false,
    }, // 是否有新增按钮
    needexport: {
      type: Boolean,
      default: false,
    },
    needReset: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      show: false,
      icon: "el-icon-arrow-down",
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; //如果没有后面的-8.64e7就是不可以选择今天的
        }
      },
      tempSearchForm: JSON.parse(JSON.stringify(this.searchForm))
    };
  },
  computed: {},
  created () {
    // 获取query历史值，并重新加载
    var queryData = getPreSubmitData() 
    Object.keys(queryData).map((item) => { 
      if(this.title[item] && this.title[item].changeType){
        queryData[item] = Number(queryData[item])
      }
      if(this.title[item] && this.title[item].multiple){
        queryData[item] = queryData[item].split(',').map((i) => {
          return Number(i)
        })
      }
    })
    this.$emit("submit", queryData)
  },
  methods: {
    // 搜索显示
    toshow() {
      this.show = !this.show;
      if (this.show) {
        this.icon = "el-icon-arrow-up";
      } else {
        this.icon = "el-icon-arrow-down";
      }
    },
    // 新增点击
    toAdd() {
      this.$emit("add");
    },
    // 导出
    toExport(){
      Object.keys(this.searchForm).forEach(item => {
        if (this.searchForm[item] === 0) {
        } else if (this.searchForm[item] == "") {
          delete this.searchForm[item];
        }
      });
      this.$emit("toExport", this.searchForm)
    },
    /**
     * 下拉框选择事件
     */
    change(data) {
      this.$emit("selectChange", data);
    },
    /**
     * 搜索
     */
    submitForm() {
      Object.keys(this.searchForm).forEach(item => {
        if (this.searchForm[item] === 0) {
        } else if (this.searchForm[item] == "") {
          delete this.searchForm[item];
        }
      });
      this.searchForm.pn = 1;
      this.$emit("submit", this.searchForm);
      this.addHrefQuery(this.searchForm)
    },
    /**
     * 重置
     */
    resetForm(formName) {
      this.$emit("reset", this.searchForm);
    },
    /**
     * 添加搜索条件到query中，以便刷新时获取
     */
    addHrefQuery (data) {
      var tempStr = '';
      if (location.href.indexOf('?') < 0) {
        tempStr = location.href;
      } else {
        var queryTemp = urlToObj(location.href);
        tempStr = location.href.split('?')[0];
        // 处理搜索参数之外的页面跳转的参数
        Object.keys(queryTemp).forEach((key) => {
          if (data[key] === undefined && this.tempSearchForm[key] === undefined) {
            data[key] = queryTemp[key];
          }
        });
      }
      // 添加表单的搜索条件并更新href
      history.replaceState({}, '', tempStr + objToUrl(data))
    }

  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang='less' scoped>
.el-input,
.el-select,
.el-textarea {
  width: 270px;
}
.el-date-editor{
  width: 400px;
  .el-range-input{
    width: 150px;
  }
}
.body {
  // padding: 0 10px;
  .search {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    // margin: 10px;
    border-bottom: 1px solid #eee;
  }
  .reset{
    width: 70px;
  }
  .el-form {
    margin: 10px;
    display: flex;
    flex-wrap:  wrap;
    .search-item{
      width: 50%;
    }
    .search-ope{
      width: 80%;
    }
    .button {
      padding: 15px;
      border-top: 1px solid #eee;
      border-bottom: 1px solid #eee;
    }
  }
}
</style>
